c ++类实例错误lnk2019

时间:2014-05-11 16:24:08

标签: c++

我搜索了我的问题超过3个小时但是找不到任何好的文章,所以决定在这里发一个问题来征求你的意见。我的问题是我不明白班级是如何运作的。它只是一个简单的类,但在一种情况下它不起作用。首先,下面是有效的代码


class R{
    int x, y;
public:
    R();
    R(int a, int b) : x(a), y(b) {};
    void setX(int a){ x = a; }
    void setY(int b){ y = b; }
    int getX(){ return x; }
    int getY(){ return y; }
    void display();
};
void R::display(){
// displaying x and y I removed the function because it somehow remove the rest of the code after arrow operator
}
int main(){
    R r(2,3);
    r.setX(1);
    r.setY(2);
    r.display();
}

但是当我像这样改变主体时它不起作用


int main(){
    R r;
    r.setX(1);
    r.setY(2);
    r.display();
}

我首先想到的原因可能是我没有真正创建一个实例,但发现了一个可以从网站上正常工作的代码。代码是这样的:


// overloading operators example
#include 
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int a,int b) : x(a), y(b) {}
    CVector operator + (const CVector&);
};

CVector CVector::operator+ (const CVector& param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return temp;
}

int main () {
  CVector foo (3,1);
  CVector bar (1,2);
  CVector result;
  result = foo + bar;
// displaying x and y I removed the function because it somehow remove the rest of the code after arrow operator
  return 0;
}

它也只是一个实例" CVector temp"不是" CVector temp(2,3)"但是当我不工作的时候它工作正常。

如果有人知道我错过了什么以及我的代码问题,请你给我一些建议吗?

感谢阅读和你的时间

3 个答案:

答案 0 :(得分:2)

根据您的评论,我可以推测该错误与R:: R ()的缺失定义有关。

MSVC的Error LNK2019指的是未解析的符号。符号是声明但不是已定义的任何函数,对象,变量或类型。

在这种情况下,我猜你从来没有提供R:: R ()的定义,但是你在类定义中写了它,它告诉编译器它在某处 - 这就是声明。

但是,显然,你从来没有定义它。 添加{}提供了函数的主体,这就是它与这些大括号一起工作的原因。

你也可以在外部定义R:: R() R:: display (),或者,如果编译器支持C ++ 11,则明确写R:: () = default

一旦你给链接器一个函数体,你的代码应该链接正常。

答案 1 :(得分:1)

当你把它写成

R();

这是constructor声明。您必须为每个方法提供一个定义,方法是给它一个正文(即使正文是空的,就像这里一样)。对于类方法,您可以像在此处类中一样提供正文,也可以在源(.cpp)文件中单独定义它,如

R::R(){/*your code*/}

它类似于代码  你发布了CVector CVector::operator+

答案 2 :(得分:1)

你需要一个默认的构造函数。

相关问题