微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

作业. C Book示例似乎有问题

以下代码是我的C类幻灯片的一部分. IntelliSence给了我错误,我不知道为什么.不知道为什么它不喜欢构造函数和析构函数.有人可以帮忙吗?
class Vehicle {
     friend void guest();
 private:
     string make;
     string model;
     int year;
 public:
     void Vehicle();
     void Vehicle(string,string,int);
     void ~Vehicle();
     string getMake();
 }

 void guest() {
     cout << make;
 }

 1) IntelliSense: member function with the same name as its class must be a constructor
 2) IntelliSense: member function with the same name as its class must be a constructor
 3) IntelliSense: return type may not be specified on a destructor

解决方法

构造函数和析构函数没有返回类型!应该:
Vehicle();
Vehicle(string,int);
~Vehicle();

您需要将参数传递给您的函数

void guest(const Vehicle &v)
{
    cout << v.make; //friend allows you to access 'make' directly
}

当然,您必须相应地更改好友声明

别忘了;在课程结束时

编辑

有效的完整代码

class Vehicle {
    friend void guest(const Vehicle &v);
private:
    string make;
    string model;
    int year;
public:
    Vehicle() {}
    Vehicle(string make,string model,int year) : make(make),model(model),year(year) {}
    ~Vehicle() {}
    string getMake() const {return make;}
};

void guest(const Vehicle &v) {
    cout << v.make;
}



int main()
{
    guest(Vehicle("foo","bar",10));
    return 0;
}

原文地址:https://www.jb51.cc/c/117558.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐