Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

智能指针使用应该要改一下,详细见代码 #2

Open
vipygd opened this issue Sep 20, 2017 · 1 comment
Open

智能指针使用应该要改一下,详细见代码 #2

vipygd opened this issue Sep 20, 2017 · 1 comment

Comments

@vipygd
Copy link

vipygd commented Sep 20, 2017

`// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include
#include
#include
#include
#include
using namespace std;

class Oper
{
public:
double getNumberA()
{
return x;
}
void setNumberA(double xx)
{
x = xx;
}
double getNumberB()
{
return y;
}
void setNumberB(double yy)
{
y = yy;
}
virtual double getResult()//使oper可实例化
{
return 0.0;
}
private:
double x;
double y;
};

class OperatorAdd :public Oper
{
public:
double getResult()
{
return getNumberA() + getNumberB();
}
};

class OperatorSub :public Oper
{
public:
double getResult()
{
return getNumberA() - getNumberB();
}
};

class OperatorMul :public Oper
{
public:
double getResult()
{
return getNumberA() * getNumberB();
}
};

class OperatorDiv :public Oper
{
public:
double getResult()
{
try
{
if (fabs(getNumberB()) < 1e-9)
{
throw overflow_error("Divide by zero exception");
}
}
catch (overflow_error& e)
{
cout << e.what() << " -> " << getNumberB() << endl;
}
return getNumberA() / getNumberB();
}
};

class OperFactory
{
public:
static Oper* createOper(char operChar)
{
//这边会报错
Oper oper;
switch (operChar)
{//这里原先用法不对,应将实例的类名放在模版中,结果显示正确
case '+':
oper = new OperatorAdd();
break;
case '-':
oper = new OperatorSub();
break;
case '
':
oper = new OperatorMul();
break;
case '/':
oper = new OperatorDiv();
break;
//other operation
default:
oper = NULL;
}
return oper;
}
};

void testSimpleFactoryMode()
{
shared_ptr oper(OperFactory::createOper('+'));
oper->setNumberA(1);
oper->setNumberB(2);
double res = oper->getResult();
cout << res << endl;
}

int main()
{
testSimpleFactoryMode();
return 0;
}

`

@JosanSun
Copy link
Owner

你这个代码太乱,而且也没有发现智能指针。

@bajdcc 的帮助下,现在已经能用智能指针完全代替普通指针。你可以看一下最新的代码。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants