顯示具有 Cpp 標籤的文章。 顯示所有文章
顯示具有 Cpp 標籤的文章。 顯示所有文章

2008年12月10日 星期三

VB.Net 與 C++的Class 比較 (1)

題目定VB.Net與C++
其實應該說.Net Framework與標準C++ 不過因為大家只用VB所以就下這個標題

C++的Class與.Net的最大差別就是
C++的Class instance預設以Call By Value傳值
也就是說如果傳入一個物件給function
它實際上是"複製一份物件" (這個跟.net的struct變數相同)
但是如果class定的比較大時就會有效能上的問題
幸好c++也有Call By Reference
不過有資料被更改的風險
又幸好我們可以規定傳進去的是Constant
那嚜
就可以兼顧by value與 by reference的優點!!!
例如

void foo3(const String& s);

表示傳入的String s不會被foo3給竄改
這也說明了為什麼c++ 的STL裡面的function那嚜喜歡用const修飾字^^

2008年11月9日 星期日

C++ 中的 struct 與 class 的比較


struct a : public b {
int foo_bar() {...;}
};


C++ 中的 struct 與在C語言中的struct不同
差別在於對於所繼承的類別預設存取權限的不同
struct 是 public
class 是 private

感謝秉宏大大提供正解

Reference:C++中的struct專題研究

在C++ primer一書中也有相當清楚的講解

2.8 使用關鍵字 struct P.66:
C++ 支援的另一個關鍵字也可以用來定義class型別。
...
以關鍵字class或struct定義出來的class,彼此之間唯一的差異是其預設存取層級:
struct的預設層級是public,class的預設層級是private。

15.2.5 繼承保護類別(Default Inheritance Protection Level) P.574:
如果你認為「以關鍵字struct定義」和「以關鍵字class定義」的classes另有更深層的差異,
不對,唯一差異就是成員的預設保護級別,以及衍生動作的預設保護級別。

2008年10月30日 星期四

物件陣列與初始化

物件陣列與初始化 筆記
若想要以非物件的預設建構子去初始化一個物件陣列時
要怎麼做呢
請參考底下的程式碼


#include
#include
#include
#include

using namespace std;

class car {
int price;
string name;
public:
//car():price(100), name("ford"){}
car();
car(int, string);
void show();
};

car::car()
{
price = 100;
name = "ford";
}

car::car(int i, string str)
{
price = i;
name = str;
}

void car::show()
{
cout << price << " " << name << endl;
}

int main()
{
car car1, car2(120, "bmw");

//default constructor
car1.show();
//initial by manual
car2.show();
//object array and initial by manual
car car3[5] = {car(1, "bmw z1"), car(2, "bmw z2"), car(3, "bmw z3"),
car(4, "bmw z4"), car(5, "bmw z5")};
//using vector to create 101 objects with the same value
vector car4;


for(int i = 0; i != 5; i++) {
car3[i].show();
}
for(int i = 0; i != 10; ++i) {
car4.push_back(car2);
car4[i].show();
}

//The following two ways are wrong!
//car *ptr = new car(111, "benz")[3];
//car *ptr = new car[3](111, "benz");

return 0;
}


輸出結果如下:
100 ford
120 bmw
1 bmw z1
2 bmw z2
3 bmw z3
4 bmw z4
5 bmw z5
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw
120 bmw

結論是用 car array_car[5](1, "xx")
或是 car array_car(1,"xx")[5] 都是錯的 Orz