读书人

关于const一些有关问题。

发布时间: 2013-06-26 14:29:32 作者: rapoo

关于const一些问题。。。。。。。
//: C08:ConstReturnValues.cpp
// Constant return by value
// Result cannot be used as an lvalue

class X {
int i;
public:
X(int ii = 0);
void modify();
};

X::X(int ii) { i = ii; }

void X::modify() { i++; }

X f5() {
return X();
}

const X f6() {
return X();
}

void f7(X& x) { // Pass by non-const reference
x.modify();
}

int main() {
f5() = X(1); // OK -- non-const return value
f5().modify(); // OK
//! f7(f5()); // Causes warning or error
// Causes compile-time errors:
//! f7(f5());
//! f6() = X(1);
//! f6().modify();
//! f7(f6());
} ///:~

还可以对函数复制?这个例子看的有些晕。求解释。 c++
[解决办法]
f5()返回一个X的实例,是对其赋值和函数调用

可阅读行不好。。

[解决办法]

引用:
//: C08:ConstReturnValues.cpp
// Constant return by value
// Result cannot be used as an lvalue

class X {
int i;
public:
X(int ii = 0);
void modify();
};

X::X(int ii) { i = ii; }

void X::modify() { i++; }

X f5() {
return X();
}

const X f6() {
return X();
}

void f7(X& x) { // Pass by non-const reference
x.modify();
}

int main() {
f5() = X(1); // OK -- non-const return value
f5().modify(); // OK
//! f7(f5()); // Causes warning or error
// Causes compile-time errors:
//! f7(f5());
//! f6() = X(1);
//! f6().modify();
//! f7(f6());
} ///:~

还可以对函数复制?这个例子看的有些晕。求解释。


f7(f5());函数复制是说啥?不懂你的意思。 f5返回一个临时对象,再让f7调用自然不对。

读书人网 >C++

热点推荐