首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

跟视频的程序一样,可是在VS2010总编译不通过

2013-07-01 
和视频的程序一样,可是在VS2010总编译不通过#includeiostream#includealgorithm#includevectorusing

和视频的程序一样,可是在VS2010总编译不通过
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class num
{
public:
num(){n=1;cout<<"构造函数在执行"<<endl;}
num(const num&s){n=s.n;cout<<"复制构造函数执行"<<endl;}
~num(){cout<<"析构函数在执行"<<endl;}
int get(){return n;}
void set(int i){n=i;}
const num equal(const num&r){n=r.get();return *this;}


private:
int n;
};
void main()
{
num one(2),two(11),three;
one.equal(two);
cout<<one.get()<<endl;

}
总是提示1>d:\c++\vs2010的第一个程序\vs2010的第一个程序\vs2010的第一个程序.cpp(13): error C2662: “num::get”: 不能将“this”指针从“const num”转换为“num &”

[解决办法]
问题的解决从代码的格式化开始。


# include <iostream>
# include <algorithm>
# include <vector>

using namespace std;

class num
{
public:
    num()
    {
        n = 1;
        cout << "constructor" << endl;
    }

    num(const num & s)
    {
        n = s.n;
        cout << "copy constructor" << endl;
    }

    ~num()
    {
        cout << "destrucotr" << endl;
    }

    int get() // 这里要改成int get() const,才能在const对象上调用
    {
        return n;
    }

    void set(int i)
    {
        n = i;
    }

    const num equal(const num & r)
    {
        n = r.get();
        return *this;
    }

private:
    int n;
};

int main()
{
    num one(2), two(11), three; // 注意并没有一个num(int)的构造函数,不知是否漏了
    one.equal(two);
    cout << one.get() << endl;

    return 0;
}


最后教你void main的不看也罢。

热点排行