临时变量,左值右值,右值引用及其作用一文可编译的示例代码

本文讲述了在学习C++时如何修复代码错误,包括类名大小写调整、函数声明的完善、右值引用的理解,以及如何正确使用const修饰返回值。通过实例展示了从报错到成功编译的步骤,帮助读者掌握基础概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习《临时变量,左值右值,右值引用及其作用》时,运行代码,报错,以下是修改后可以运行的代码及修改过程:

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 ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值