cpp
复制代码
#include <iostream>
using namespace std;
int &f1(int &a) {
a += a;
return a;
}
int &f2(int &b) {
b += b;
return b;
}
int main() {
int x = 10;
int y = f1(x);
int z = f2(y);
cout << x << endl << y << endl << z << endl;
return 0;
}
输出:
复制代码
20
40
40
执行过程:
函数返回类型 int&:
f2 的返回类型是 int&,表示返回一个 int 类型的引用(不是指针)。
在 return b; 这一行,f2 返回 b 的引用(即 x 的别名)。
调用 f2(x):
f2(x) 返回 x 的引用,x 的值被加倍后变为 20。
因此,f2(x) 返回了一个引用类型的值。
y = f2(x) 赋值:
虽然 f2(x) 返回的是引用,但返回的引用可以隐式转换成对应的值。
所以 y 最终获得了 20,即 x 的值。
2014读代码5
#include <iostream>
using namespace std;
class A {
private:
int a;
static int b;
public:
A(int i) { // 构造函数
a = i;
b += i;
}
void f() {
cout << "a = " << a << ", b = " << b << endl;
}
};
int A::b = 0; // 全局static变量,只开始时候执行一次
int main() {
A obj1(10);
obj1.f(); // a = 10, b = 10
A obj2(15);
obj2.f(); // a = 15, b = 25
obj1.f(); // a = 10, b = 25
return 0;
}
输出:
a = 10, b = 10
a = 15, b = 25
a = 10, b = 25
// 直接访问静态成员变量 b
cout << "Accessing static b directly: b = " << A::b << endl; // 输出: b = 25
// 访问 obj1 的 b 值
cout << "Accessing obj1's b through getB(): b = " << obj1.getB() << endl; // 输出: b = 10
static b:
访问特性:
如果成员变量 b 被声明为 static,则可以使用 A::b 直接访问它,因为静态成员变量是与类本身关联的,而不是与特定的对象实例关联。所有对象共享同一个静态成员变量。
发生时间:
静态成员变量的初始化发生在 main 函数执行之前。这意味着,在创建任何对象之前,静态成员变量就已经被初始化。
去掉:
如果你希望去掉 int A::b = 0; 这一行(即静态成员变量的定义和初始化),那么会导致代码无法编译,因为静态成员变量 b 需要在类外进行定义和初始化。静态成员变量的声明和定义是分开的,声明是在类内进行,而定义和初始化必须在类外完成。
2014读代码6
#include <iostream>
using namespace std;
class A {
private:
int a;
public:
A() {
a = 0;
cout << "A's default constructor called.\n";
}
A(int i) {
a = i;
cout << "A's constructor called.\n";
}
void print() {
cout << a << endl;
}
~A() {
cout << "A's destructor called.\n";
}
int Geta() {
return a;
}
};
class B : public A {
private:
int b;
A aa;
public:
B() : A() {
b = 0;
cout << "B's default constructor called.\n";
}
B(int i, int j, int k) : A(i), aa(j) {
b = k;
cout << "B's constructor called.\n";
}
void print() {
A::print();
cout << b << " " << aa.Geta() << endl;
}
~B() {
cout << "B's destructor called.\n";
}
};
int main() {
B bb[2] = { B(10, 15, 20), B(1, 23) };
for (int i = 0; i < 2; i++) {
bb[i].print();
}
return 0;
}