简体   繁体   中英

Question about implementing abstract functions in C++?

I am learning and testing a piece of C++ code as follows:

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <conio.h>
#include <cstring>
class Shape {
public:
    Shape() {};
    ~Shape() {};
    virtual void display() const = 0;
    virtual double volume() const = 0;
};

class Square : public Shape {
public:
    Square() {};
    ~Square() {};
    void display() const;
    double volume() const;
};

void Square::display() const {
    cout << "Square!!!!!!!!!!!!!!" << endl;
}
double Square::volume() const {
    cout << "Square Volume........." << endl;
    return 0.0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    Shape *s;
    s = new Square; // error here
    (*s).display();

    return 0;
}

The above code does not compile successfully. it produces: " fatal error LNK1120: 1 unresolved externals ". Can anyone help me out with that? I am using MS VS C++ 2005. Thanks

The above code compiles and runs properly on VS 2010 as well as Ideone.

Check this

There is nothing wrong in the way you have implemented your abstract functions in the above snippet.

I'm pretty sure your problem is your main declaration.

If you change it to a standard main definition, I believe your linking problems will be fixed.

 int main()
 {
   Shape *s = new Square(); // error here
   s->display();
   return 0;
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM