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

前端之家收集整理的这篇文章主要介绍了作业. 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;
}

猜你在找的C&C++相关文章