having difficulties to make a vector of polymorphic objects using shared_ptr and unique_ptr in C++ Visual studio 2019 Cmake project

吃可爱长大的小学妹 提交于 2020-05-16 03:54:08

问题


For an exercise i need to build a vector of polymorphic objects and for some reason both shared and Unique ptr make linkage errors 2019 and 1120 when i use them. i have no option to use the old way of memory allocation with New and Delete so i have to make it work. i tried various of different syntax options for doing this and still with no luck.

*note: we use Cmake to bind the project together in visual studio
and also we splitting the objects into header and cpp files.

here are my objects for now:

//This is the abstract base class
#pragma once
#include <string>

class Shape
{
public:
    Shape() = default;
    virtual ~Shape() = default;
    virtual std::string get_name() = 0;

private:

};

These are the derived classes:

#pragma once
#include "Shape.h"

class Circle : public Shape
{
public:
    Circle();
    ~Circle();
    virtual std::string get_name() override;

private:
    std::string m_name;
};

Cpp file:

#pragma once
#include "Circle.h"

Circle::Circle()
    : m_name("Circle")
{
}

Circle::~Circle()
{
}

std::string Circle::get_name() override
{
    return m_name;
}

another derived class:

#pragma once
#include "Shape.h"

class Rectangle : public Shape
{
public:
    Rectangle();
    ~Rectangle();
    virtual std::string get_name() override;

private:
    std::string m_name;
};

Cpp file:

#pragma once

#include "Rectangle.h"

Rectangle::Rectangle()
    : m_name ("Rectangle")
{
}

Rectangle::~Rectangle()
{
}

std::string Rectangle::get_name() override
{
    return m_name;
}

this is the class that operates the program:

#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include "Shape.h"
#include "Circle.h"
#include "Rectangle.h"

class Board
{
public:
    Board();
    ~Board();
void run();
    void objects_allocation();

private:

    std::string m_string;
    std::vector<std::shared_ptr<Shape>> m_gates;

};

Cpp file:

#pragma once
#include "Board.h"

Board::Board()
    : m_string(" ")
{
}

Board::~Board()
{
}

void run()
{

    while (m_string != "exit")
    {
        std::cin >> m_string;
    }

    std::cout << "Goodbye!" << std::endl;
}
void Board::Objects_allocation()
{
    m_gates.push_back(std::make_shared <Circle>());
    m_gates.push_back(std::make_shared <Rectangle>());
}

and here is my main function:

#pragma once

#include "Board.h"

int main()
{
    Board board1;
    board1.run();

    return 0;
}

sincerely thank you if you could explain to me what went wrong here..


回答1:


The Problem was in the Cmake file. now everything is working just like i wanted.



来源:https://stackoverflow.com/questions/61174719/having-difficulties-to-make-a-vector-of-polymorphic-objects-using-shared-ptr-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!