C++---前向声明应用注意

  在设计模式中,简单工厂模式中一个是Product类(产品类),一个是ProductManager类(工厂类),而两个类互相引用了,形成了环形引用,而前向声明可以解决这个问题,但是在应用前向声明的时候需要注意一点就是,声明仅仅是声明,并没有实现,因此不能调用声明的变量的方法或者实现该类。举例如下:

去掉注释就是正确的前向声明,没有去掉注释就是错误的前向声明应用

编译

g++ main.cpp product.cpp product_manager.cpp -I. -std=c++11

文件

  product.h

#pragma once

#include <string>

using namespace std;

class ProductManager;

// Product
class Product {
public:
    Product(ProductManager *_manager, string _name);

    string getName();

    void setName(string _name);

private:
    string name;
    bool canChanged = false;


};

  product.cpp

#include "product.h"

Product::Product(ProductManager *_manager, string _name) {
    // error: invalid use of incomplete type 'class ProductManager'
//    if(_manager->isCreateProduct()) {
//        canChanged = true;
//        this->name = _name;
//    }
}

string Product::getName() {
    return name;
}

void Product::setName(string _name) {
    if(canChanged) {
        this->name = _name;
    }
}

  product_manager.h

#pragma once

#include <string>

using namespace std;

class Product;

class ProductManager {
public:
    Product* createProduct(string _name);

    void abandonProduct(Product *p);

    void editProduct(Product *p, string _name);

    bool isCreateProduct();

private:
    bool isPermittedCreate = false;

};

  product_manager.cpp

#include "product_manager.h"


Product* ProductManager::createProduct(string _name) {
    isPermittedCreate = true;
    // error: invalid use of incomplete type 'class Product'
//    Product *p = new Product(this, _name);
//    return p;
    return NULL;
}

void ProductManager::abandonProduct(Product *p) {
    // warning: possible problem detected in invocation of delete operator
    // delete p;
}

void ProductManager::editProduct(Product *p, string _name) {
    // error: invalid use of incomplete type 'class Product'
    //p->setName(_name);
}

bool ProductManager::isCreateProduct() {
    return isPermittedCreate;
}

  main.cpp

#include <iostream>
#include <string>

#include "product_manager.h"
#include "product.h"

using namespace std;


int main()
{

    return 0;
}

  当然,工厂模式真正的实现并非如此潦草,肯定需要结合多态。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值