面试题答案
一键面试package main
import (
"fmt"
)
// 定义图形类型枚举
type ShapeType int
const (
Circle ShapeType = iota
Rectangle
Triangle
)
// 定义表示几何图形的结构体
type Shape struct {
shapeType ShapeType
// 使用结构体嵌入来存储不同图形的参数
case Circle:
radius float64
case Rectangle:
length float64
width float64
case Triangle:
base float64
height float64
}
// 初始化函数
func NewShape(shapeType ShapeType, params ...float64) Shape {
var s Shape
s.shapeType = shapeType
switch shapeType {
case Circle:
if len(params) != 1 {
panic("Circle requires 1 parameter (radius)")
}
s.radius = params[0]
case Rectangle:
if len(params) != 2 {
panic("Rectangle requires 2 parameters (length and width)")
}
s.length = params[0]
s.width = params[1]
case Triangle:
if len(params) != 2 {
panic("Triangle requires 2 parameters (base and height)")
}
s.base = params[0]
s.height = params[1]
}
return s
}
以下是简单测试代码:
func main() {
circle := NewShape(Circle, 5.0)
rectangle := NewShape(Rectangle, 4.0, 3.0)
triangle := NewShape(Triangle, 6.0, 4.0)
fmt.Printf("Circle: radius = %.2f\n", circle.radius)
fmt.Printf("Rectangle: length = %.2f, width = %.2f\n", rectangle.length, rectangle.width)
fmt.Printf("Triangle: base = %.2f, height = %.2f\n", triangle.base, triangle.height)
}
上述代码在Go语言中定义了一个表示几何图形的结构体Shape
,其中使用枚举类型ShapeType
表示图形类型,并通过NewShape
函数根据传入的图形类型及对应参数正确初始化Shape
结构体。
在其他语言如C++中,代码示例如下:
#include <iostream>
#include <variant>
// 定义图形类型枚举
enum class ShapeType {
Circle,
Rectangle,
Triangle
};
// 定义表示几何图形的结构体
struct Shape {
ShapeType shapeType;
std::variant<double, std::pair<double, double>> params;
// 初始化函数
Shape(ShapeType type, double param1 = 0, double param2 = 0) : shapeType(type) {
switch (type) {
case ShapeType::Circle:
params = param1;
break;
case ShapeType::Rectangle:
case ShapeType::Triangle:
params = std::make_pair(param1, param2);
break;
}
}
};
以下是简单测试代码:
int main() {
Shape circle(ShapeType::Circle, 5.0);
Shape rectangle(ShapeType::Rectangle, 4.0, 3.0);
Shape triangle(ShapeType::Triangle, 6.0, 4.0);
if (std::holds_alternative<double>(circle.params)) {
std::cout << "Circle: radius = " << std::get<double>(circle.params) << std::endl;
}
if (std::holds_alternative<std::pair<double, double>>(rectangle.params)) {
auto [length, width] = std::get<std::pair<double, double>>(rectangle.params);
std::cout << "Rectangle: length = " << length << ", width = " << width << std::endl;
}
if (std::holds_alternative<std::pair<double, double>>(triangle.params)) {
auto [base, height] = std::get<std::pair<double, double>>(triangle.params);
std::cout << "Triangle: base = " << base << ", height = " << height << std::endl;
}
return 0;
}
在C++代码中,使用enum class
定义图形类型枚举,std::variant
来存储不同图形的参数,并通过构造函数进行初始化。