Day 19: Interfaces

题目:

C++:

#include <stdio.h>

#include <stdlib.h>

#include <algorithm>

#include <string>

#include <math.h>

#include <vector>

#include <map>

#include <stack>

#include <queue>

#include <exception>

#include <stdexcept>

#include <iostream>

using namespace std;

class AdvancedArithmetic {

public:

virtual int divisorSum(int n) = 0; //纯虚函数

};

class Calculator :public AdvancedArithmetic {

public:

int divisorSum(int n) { //在派生类中实现纯虚函数

int sum = 0;

for (int i = 1; i <= n; i++) {

if (n % i == 0) {

sum += i;

}

}

return sum;

}

};

int main() {

int n;

cin >> n;

AdvancedArithmetic *myCalculator = new Calculator(); //这里使用磨人的构造函数,对象需要使用指针类型

int sum = myCalculator->divisorSum(n);

cout << "I implemented: AdvancedArithmetic\n" << sum;

system("pause");

return 0;

}

python:

class AdvancedArithmetic(object):

def divisorSum(n):

raise NotImplementedError

class Calculator(AdvancedArithmetic): //继承

def divisorSum(self, n): //覆盖基类的函数

sum=0

for i in range(1,n+1):

if n % i == 0:

sum += i

return sum

n = int(input())

my_calculator = Calculator()

s = my_calculator.divisorSum(n)

print("I implemented: " + type(my_calculator).__bases__[0].__name__) //输出基类的名称

print(s)

总结:

C++:

纯虚函数,有纯虚函数的类是抽象类,抽象类不能实现纯虚函数,需要派生类来实现。

virtual int divisorSum(int n) = 0; //关键字virtual,并且后面写个0,不写0的为虚函数

 

python:

类的继承,派生类覆盖基类的函数

class Calculator(AdvancedArithmetic):

 

以上是 Day 19: Interfaces 的全部内容, 来源链接: utcz.com/a/54170.html

回到顶部