C++ 成员初始值设定项列表问题:私有成员变量的声明顺序
C++ Member Initializer Lists Problem: Declaration Order on Private Member Variables
这是我在 Stack Overflow 上发布的第一个问题,希望有人能解释一下。
所以基本上这两个 类 除了私有成员变量的顺序之外是一样的。输出是10 20 10 0
我不明白为什么声明的顺序会影响输出。
#include <iostream>
using namespace std;
class MyClass{
public:
MyClass(int value): b(value), a(b * 2){
cout << b << " " << a << " ";
}
private:
int b;
int a;
};
class YourClass{
public:
YourClass(int value): d(value), c(d * 2){
cout << d << " " << c << " ";
}
private:
int c;
int d;
};
int main(){
MyClass obj(10);
YourClass OBJ(10);
}
Class 成员按照声明的顺序进行初始化。
Initialization Order of Class Data Members
#include <iostream>
class MyClass{
public:
MyClass(int value): b(value++), a(value++){
std::cout << b << " " << a << " " << std::endl;
}
private:
int b;
int a;
};
class YourClass{
public:
YourClass(int value): b(value++), a(value++){
std::cout << b << " " << a << " " << std::endl;
}
private:
int a;
int b;
};
int main(){
MyClass obj(10);
YourClass OBJ(10);
}
输出:
10 11
11 10
这是我在 Stack Overflow 上发布的第一个问题,希望有人能解释一下。
所以基本上这两个 类 除了私有成员变量的顺序之外是一样的。输出是10 20 10 0
我不明白为什么声明的顺序会影响输出。
#include <iostream>
using namespace std;
class MyClass{
public:
MyClass(int value): b(value), a(b * 2){
cout << b << " " << a << " ";
}
private:
int b;
int a;
};
class YourClass{
public:
YourClass(int value): d(value), c(d * 2){
cout << d << " " << c << " ";
}
private:
int c;
int d;
};
int main(){
MyClass obj(10);
YourClass OBJ(10);
}
Class 成员按照声明的顺序进行初始化。
Initialization Order of Class Data Members
#include <iostream>
class MyClass{
public:
MyClass(int value): b(value++), a(value++){
std::cout << b << " " << a << " " << std::endl;
}
private:
int b;
int a;
};
class YourClass{
public:
YourClass(int value): b(value++), a(value++){
std::cout << b << " " << a << " " << std::endl;
}
private:
int a;
int b;
};
int main(){
MyClass obj(10);
YourClass OBJ(10);
}
输出:
10 11
11 10