学习《临时变量,左值右值,右值引用及其作用》时,运行代码,报错,以下是修改后可以运行的代码及修改过程:
1.修改Base类定义
(1)修改前
Class Base(){
报错内容:
test.cpp:11:1: error: ‘Class’ does not name a type; did you mean ‘class’?
Class Base(){
^~~~~
class
(2)修改后
把Class修改为全小写关键字class
test.cpp:11:12: error: expected unqualified-id before ‘)’ token
class Base(){
^
把类名Base后面的小括号去掉
class Base {
2.修改Bar函数定义
(1)修改前:
virtual Bar() { cout << "base bar()" << endl; }
编译不过,报错:
test.cpp:13:22: error: ISO C++ forbids declaration of ‘Bar’ with no type [-fpermissive]
virtual Bar() { cout << "base bar()" << endl; }
(2)修改后:
增加函数返回类型void
virtual void Bar() { cout << "base bar()" << endl; }
3.修改Bar函数的返回值为const
(1)修改前:
virtual void Bar() { cout << "base bar()" << endl; }
编译器以为要修改返回值,所以报错。
编译报错如下:
test.cpp: In function ‘int main()’:
test.cpp:48:14: error: passing ‘const Base’ as ‘this’ argument discards qualifiers [-fpermissive]
ref1.Bar();
(2)修改后
增加返回值为const类型,这样调用 ref1.Bar() 就不会报错了。
virtual void Bar() const { cout << "base bar()" << endl; }
4.完整代码:
#include <string>
#include <iostream>
using namespace std;
string Proc(){
return string("abc");
}
class Base {
public:
virtual void Bar() const { cout << "base bar()" << endl; }
};
class DerOne: public Base {
public:
virtual void Bar() const { cout << "DerOne Bar()" << endl; }
};
class DerTwo: public Base {
public:
virtual void Bar() const { cout << "DerTwo Bar()" << endl; }
};
Base GetBase() {
return Base();
}
DerOne GetDerOne() {
return DerOne();
}
DerTwo GetDerTwo() {
return DerTwo();
}
int main() {
cout << "▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼ main BEGIN ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼" << endl;
const string& ref = Proc();
cout << ref << endl;
const Base& ref1 = GetBase();
const Base& ref2 = GetDerOne();
const Base& ref3 = GetDerTwo();
ref1.Bar();
ref2.Bar();
ref3.Bar();
cout << "▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ main END ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲" << endl;
return 0;
}
(1)编译:
/cplusplusTest$ g++ test.cpp -o test
编译完无任何报错输出
(2)运行结果:
./test
▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼ main BEGIN ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
abc
base bar()
DerOne Bar()
DerTwo Bar()
▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ main END ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲